package com.yundasys.lab08jvm.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author jiangta
 * @version 1.0
 * @date 2021/5/20 1:45 下午
 */
public class SyncLock {

    private Sync sync = null;

    public SyncLock() {
        sync = new Sync();
    }

    public void lock() {
        sync.acquire(1);
    }

    public void unlock() {
        sync.release(1);
    }


    private static class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            return compareAndSetState(0,1);
        }

        @Override
        protected boolean tryRelease(int arg) {
            setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getState() ==1;
        }
    }
}
